package controll;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.SwingUtilities;

import model.Snake;
import view.GamePanel;

public class MainFrame extends JFrame implements ActionListener{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private GamePanel gamePanel;
	private Snake snake;
	
	public MainFrame() {
		setSize(700, 558);
		setVisible(true);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		String[] menus={"游戏","速度","帮助"};
		String[][] items={{"新游戏","暂停","继续","退出"},{"慢速","中速","快速"},{"关于"}};
		JMenuBar mb=new JMenuBar();
		for(int i=0;i<menus.length;i++){
			JMenu m=new JMenu(menus[i]);
			for(int j=0;j<items[i].length;j++){
				JMenuItem item=new JMenuItem(items[i][j]);
				m.add(item);
				item.addActionListener(this);
			}
			mb.add(m);
		}
		setJMenuBar(mb);
		
		setLayout(null);
		setResizable(false);

		snake=new Snake();
		snake.openMoveThread();
		gamePanel=new GamePanel();
		gamePanel.setLocation(0, 0);
		add(gamePanel);
		
		addKeyListener(new KeyAdapter() {
			@Override
			public void keyPressed(KeyEvent e) {
				// TODO Auto-generated method stub
				super.keyPressed(e);
				switch (e.getKeyCode()) {
				case KeyEvent.VK_UP:
					snake.changeDirection(Snake.UP);
					break;
				case KeyEvent.VK_DOWN:
					snake.changeDirection(Snake.DOWN);
					break;
				case KeyEvent.VK_LEFT:
					snake.changeDirection(Snake.LEFT);
					break;
				case KeyEvent.VK_RIGHT:
					snake.changeDirection(Snake.RIGHT);
					break;
				}
			}
		});
	}	
	
	public static void main(String[] args) {
		SwingUtilities.invokeLater(new Runnable() {
			
			@Override
			public void run() {
				new MainFrame();
			}
		});
	}

	@Override
	public void actionPerformed(ActionEvent e) {
		String cmd=e.getActionCommand();
		switch (cmd) {
		case "新游戏":
			snake.addObserver(gamePanel);
			snake.init();						
			break;
		}
	}

}
